package fct.mpc.utils;

public class Polygon 
{ 
    // Polygon coodinates. 
    private int[] polyY, polyX; 
 
    // Number of sides in the polygon. 
    private int polySides; 
 
    /** 
     * Default constructor. 
     * @param px Polygon y coods. 
     * @param py Polygon x coods. 
     * @param ps Polygon sides count. 
     */ 
    public Polygon( int[] px, int[] py, int ps ) 
    { 
        polyX = px; 
        polyY = py; 
        polySides = ps; 
    } 
 
    public int minX()
    {
    	int min = Integer.MAX_VALUE;  	
    	for(int i=0; i<polySides; i++)
    		min = Math.min(min, polyX[i]);

    	return min;
    }
    
    public int maxX()
    {
    	int max = Integer.MIN_VALUE;    	
    	for(int i=0; i<polySides; i++)
    		max = Math.max(max, polyX[i]);
    	
    	return max;
    }
    
    public int minY()
    {
    	int min = Integer.MAX_VALUE;
    	for(int i=0; i<polySides; i++)
    		min = Math.min(min, polyY[i]);
    	
    	return min;
    }
    
    public int maxY()
    {
		int max = Integer.MIN_VALUE;	
    	for(int i=0; i<polySides; i++)
    		max = Math.max(max, polyY[i]);
    	
    	return max;
    }
    
    /** 
     * Checks if the Polygon contains a point. 
     * @see "http://alienryderflex.com/polygon/" 
     * @param x Point horizontal pos. 
     * @param y Point vertical pos. 
     * @return Point is in Poly flag. 
     */ 
    public boolean contains( int x, int y ) 
    { 
        boolean oddTransitions = false; 
        for( int i = 0, j = polySides -1; i < polySides; j = i++ ) 
        { 
            if( ( polyY[ i ] < y && polyY[ j ] >= y ) || ( polyY[ j ] < y && polyY[ i ] >= y ) ) 
            { 
                if( polyX[ i ] + ( y - polyY[ i ] ) / ( polyY[ j ] - polyY[ i ] ) * ( polyX[ j ] - polyX[ i ] ) < x ) 
                    oddTransitions = !oddTransitions;
            } 
        } 
        
        return oddTransitions; 
    }   
}
